
import paho.mqtt.client as mqtt
from paho.mqtt.client import CallbackAPIVersion
from models import db, Data
from datetime import datetime
import json
import random
from flask import current_app
import logging


MQTT_PORT = 1883
MQTT_BROKER = "127.0.0.1"
MQTT_TOPIC = "iot/sensor/data"
CLIENT_ID = f"data_subscriber_{random.randint(0, 1000)}"
logging.basicConfig(level=logging.INFO)

# 将收到的环境数据提交到mysql中
def on_message(client, userdata, msg):
    if msg.topic == MQTT_TOPIC:
        try:
            payload = json.loads(msg.payload.decode())
            timestamp = payload.get("timestamp")
            data_values = payload.get("data")

            if data_values and len(data_values) == 3:
                with userdata['app'].app_context():
                    new_data = Data(
                        temp=data_values[0],
                        humidity=data_values[1],
                        light=data_values[2],
                        timestamp=datetime.fromisoformat(timestamp.split('+', 1)[0] + "+00:00") if timestamp else None
                    )
                    db.session.add(new_data)
                    db.session.commit()
                    print(f"保存数据: {new_data}")
        except Exception as e:
            print(f"[错误] 存储传感器数据失败: {e}")
            with userdata['app'].app_context():
                db.session.rollback()

def start_mqtt_client(app):
    

    logging.info("MQTT 客户端正在启动...")

    client = mqtt.Client(
        callback_api_version=CallbackAPIVersion.VERSION2,
        client_id=CLIENT_ID
    )
    client.user_data_set({'app': app})
    client.on_message = on_message
    client.connect(MQTT_BROKER, MQTT_PORT)
    client.subscribe(MQTT_TOPIC)
    logging.info(f"MQTT 已订阅主题: {MQTT_TOPIC}")


    client.loop_forever()